package scc.project.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scc.project.dao.GoodsDao;
import scc.project.dao.StockInfoDao;
import scc.project.entity.Goods;
import scc.project.entity.StockInfo;
import scc.project.entity.vo.PageVo;
import scc.project.entity.vo.StockInfoVo;

import java.util.ArrayList;
import java.util.List;

/**
 * 进货的业务类
 *
 * @author 陈圳佳
 */
@Service
public class StockInfoService {

    @Autowired
    private StockInfoDao stockInfoDao;
    @Autowired
    private GoodsDao goodsDao;

    /**
     * 查询
     */
    public PageVo<StockInfo> find(Integer page, String code) {
        PageVo<StockInfo> pageVo = new PageVo<StockInfo>(page);
        List<StockInfo> stockInfos = stockInfoDao.find(pageVo.getOffset(), pageVo.getRows(), code);
        pageVo.setData(stockInfos);
        pageVo.addParam("code", code);
        Long total = stockInfoDao.findTotal(code);
        pageVo.setTotal(total);
        return pageVo;
    }


    public boolean save(StockInfoVo stockInfo) {
        Double totalPrice = 0d;
        List<Stock> stocks = new ArrayList<Stock>();
        for (Goods goods : stockInfo.getGoodsList()) {
            Goods byName = goodsDao.getByName(goods.getGoodsName());
            int i;
            long id;
            if (byName == null) {
                i = goodsDao.insert(goods);
                totalPrice += goods.getOutPrice();
                id = goods.getId();
            } else {
                i = goodsDao.updateNumberById(goods.getNumber(), byName.getId());
                totalPrice += byName.getOutPrice();
                id = byName.getId();
            }
            stocks.add(new Stock(id, goods.getNumber()));
            if (i <= 0) throw new RuntimeException("添加商品失败了");
        }
        stockInfo.setDealPrice(totalPrice);
        String code = stockInfoDao.selectCode(stockInfo.getStockDate());
        stockInfo.setCode(code);
        stockInfoDao.insert(stockInfo);
        for (Stock s : stocks) {
            stockInfoDao.insertForeign(stockInfo.getId(), s.getId(), s.getTotal());
        }
        return true;
    }

    class Stock {
        private Long id;
        private Integer total;

        public Stock(Long id, Integer total) {
            this.id = id;
            this.total = total;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public Integer getTotal() {
            return total;
        }

        public void setTotal(Integer total) {
            this.total = total;
        }
    }
}
